import React from "react";
import { Form, Input, Button, Select, Card, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { useUser } from "../../contexts/UserContext";

interface LoginForm {
  username: string;
  password: string;
  role: "admin" | "teacher" | "student";
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const { login } = useUser();

  const onFinish = async (values: LoginForm) => {
    try {
      await login(values.username, values.password, values.role);
      message.success("登录成功");

      // 根据角色跳转到不同的首页
      switch (values.role) {
        case "admin":
          navigate("/admin");
          break;
        case "teacher":
          navigate("/teacher");
          break;
        case "student":
          navigate("/student");
          break;
        default:
          navigate("/");
      }
    } catch (error) {
      message.error("登录失败");
    }
  };

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        minHeight: "100vh",
        background: "#f0f2f5",
      }}
    >
      <Card style={{ width: 400 }}>
        <h2 style={{ textAlign: "center", marginBottom: 24 }}>教学管理系统</h2>
        <Form<LoginForm>
          name="login"
          initialValues={{ role: "teacher" }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              size="large"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>
          <Form.Item
            name="role"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            <Select size="large">
              <Select.Option value="admin">管理员</Select.Option>
              <Select.Option value="teacher">教师</Select.Option>
              <Select.Option value="student">学生</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
